import json

from flask import Flask, render_template, request, flash, url_for, jsonify, session
from werkzeug.utils import redirect

import connMysql

app = Flask(__name__)
app.secret_key = '3210611037'  # 设置密钥


@app.route("/", methods=["GET", "POST"])
def login():
    if request.method == "GET":
        return render_template("login.html")
    else:
        username = request.form.get("username")  # 接收POST请求发来的数据
        password = request.form.get("password")
        user_type = request.form.get('user-type')


        session['username'] = username

        if user_type == 'admin':
            res = connMysql.login_manager(username, password)
            if res == "ok":
                flash('管理员登陆成功', 'admin_success')
                return redirect(url_for("manager_dashboard", username=username))
            elif res == "false":
                flash('管理员登录失败，请检查用户名和密码', 'admin_failed')
                return redirect(url_for("login"))
                # return render_template("login.html")
        elif user_type == 'user':
            res = connMysql.login_user(username, password)
            if res == "ok":
                flash('用户登陆成功', 'user_success')
                return redirect(url_for("user_dashboard"))
            elif res == "false":
                flash('用户登录失败，请检查用户名和密码', 'user_failed')
                return redirect(url_for("login"))
                # return render_template("login.html")
        else:
            # 其他情况，弹窗提示
            flash('请选择用户类型', 'error')
            return redirect(url_for("login"))
            # return render_template("login.html")


@app.route("/register", methods=["GET", "POST"])
def register():
    if request.method == "GET":
        return render_template("register.html")
    else:
        name = request.form.get("name")  # 接收POST请求发来的数据
        username = request.form.get("username")
        password = request.form.get("password")
        phone = request.form.get("phone")
        confirm_password = request.form.get("confirm-password")
        # print(name, username, password, phone)

        if password != confirm_password:
            flash('两次输入的密码不匹配，请重新输入', 'error')
            return redirect(url_for('register'))

        res = connMysql.register(name, username, password, phone)

        if res == "用户已经存在":
            flash("用户已存在", 'exist')
            return redirect(url_for("register"))  # url重定向
            # return render_template("register.html")
        elif res == "注册成功":
            flash("注册成功", 'success')
            return redirect(url_for("register"))
            # return render_template("register.html")
        else:
            flash("注册失败，请重试", "error")
            # return render_template("register.html")
            return redirect(url_for("register"))


@app.route('/manager/dashboard')
def manager_dashboard():
    username = session.get('username')
    return render_template("manager_dashboard.html", username=username)


@app.route('/user/dashboard', methods=["GET", "POST"])
def user_dashboard():
    username = session.get('username')
    # 展示菜单信息
    dishes = connMysql.show_dishes()
    return render_template("user_dashboard.html", username=username, dishes=dishes)


# 后端响应下单请求接口
# 查询余额是否充足
@app.route('/purchasable', methods=["POST"])
def purchasable():
    check = request.json["check"]
    total_price = request.json["total_price"]
    try:
        result = connMysql.is_purchasable(check, total_price)
        return result
    except Exception as e:
        # 处理异常，返回错误的响应
        return jsonify({"status": "error", "message": str(e)})


# 执行下单操作
@app.route('/place_order', methods=["POST"])
def place_order():
    cart = request.json  # 前端使用JSON格式发送购物车信息
    # print(cart)
    username = session.get('username')
    try:
        # 获取购物车中的菜品信息
        # 在这里遍历购物车信息，更新数据库中的库存和销量
        for item in cart:
            dish_id = item['id']
            dish_name = item['name']
            dish_price = item['price']
            connMysql.update_database(dish_id, dish_name, dish_price, username, cart)
        # print("下单成功")
        return jsonify({"status": "success"})
    except Exception as e:
        # 处理异常，返回错误的响应
        # print("下单失败")
        return jsonify({"status": "error", "message": str(e)})


@app.route('/show_users', methods=["GET"])
def show_users():
    users = connMysql.show_users()
    # print(jsonify(users))
    return jsonify(users)


# 删除用户接口
@app.route('/delete_users', methods=["POST"])
def delete_users():
    print(request.json, "####")
    print(type(request.json))
    Uid = request.json["id"]
    result = connMysql.delete_users(Uid)
    # print(Uid)
    # print(result)
    return result
    # return jsonify({"msg": "success"})
    # return jsonify(result)


@app.route('/show_dishes', methods=["GET"])
def show_dishes():
    dishes = connMysql.show_dishes()
    # print(dishes)
    return jsonify(dishes)


@app.route('/delete_dishes', methods=["POST"])
def delete_dishes():
    Did = request.json["id"]
    result = connMysql.delete_dishes(Did)
    return result


@app.route('/show_orders', methods=["GET"])
def show_orders():
    dishes = connMysql.show_orders()
    return jsonify(dishes)


@app.route('/delete_order', methods=["POST"])
def delete_order():
    Oid = request.json["id"]
    # print(Oid)
    result = connMysql.delete_orders(Oid)
    return result


# 添加用户接口
@app.route('/add_user', methods=["POST"])
def add_user():
    Uname = request.json["name"]
    Uusername = request.json["username"]
    Upassword = request.json["password"]
    Uphone = request.json["phone"]
    result = connMysql.add_user(Uname, Uusername, Upassword, Uphone)
    return result


# 添加菜品接口
@app.route('/add_dish', methods=["POST"])
def add_dish():
    Dname = request.json["name"]
    Dprice = request.json["price"]
    Dsale = request.json["sale"]
    Dinv = request.json["inv"]
    result = connMysql.add_dish(Dname, Dprice, Dsale, Dinv)
    return result


# 用户修改数据接口
@app.route('/mod_user', methods=["POST"])
def mod_user():
    Uname = request.json["name"]
    Uusername = request.json["username"]
    Upassword = request.json["password"]
    Uphone = request.json["phone"]
    check = request.json["check"]
    result = connMysql.mod_user(Uname, Uusername, Upassword, Uphone, check)
    return result


# 我的钱包接口
# 显示当前存款
@app.route('/show_account', methods=["POST"])
def show_account():
    username = request.json["check"]
    result = connMysql.show_account(username)
    return result


# 充值
@app.route('/wallet', methods=["POST"])
def wallet():
    username = request.json["check"]
    account = request.json["account"]
    result = connMysql.user_wallet(username, account)
    return result


# 用户查询订单
@app.route('/my_order', methods=["GET", 'POST'])
def my_order():
    username = session.get('username')
    # 展示菜单信息
    myOrders = connMysql.show_my_order(username)
    print(myOrders)
    return jsonify(myOrders)
    # return render_template("user_dashboard.html", orders=myOrders)


# 查询菜品接口
@app.route('/search_dish', methods=['POST'])
def search_dish():
    data = request.get_json()
    # 从前端获取用户输入的关键字
    keyword = data.get('keyword', '')
    # 查询数据库，获取符合关键字的菜品信息
    result = connMysql.search_dish(keyword)
    return jsonify(result)


# 管理员账本
@app.route('/ledger', methods=['GET'])
def ledger():
    data = connMysql.account_book()
    return jsonify(data)


if __name__ == '__main__':
    app.run(debug=True)
